<template>
	<treeselect v-model="deptId" :appendToBody="true" :default-expand-level="5" :options="deptOptions"
		:clearable="false" :isDefaultExpanded="true" :show-count="true" :placeholder="tips" :style="'width:' + width"
		@select="change" :disabled="able" :disable-branch-nodes="branchNodes" :normalizer="normalizer" :flat="true" />

</template>

<script>
	import {
		deptTreeSelect
	} from "@/api/system/user";
	import Treeselect from "@riophae/vue-treeselect";
	import "@riophae/vue-treeselect/dist/vue-treeselect.css";
	import Cookies from "js-cookie";
	export default {
		components: {
			Treeselect
		},
		props: {
			level: {
				type: Number,
				default: 3
			},
			/**
			 * 在清除所有输入字段之前进行处理的函数。
			 * 返回“false”以防止清除值
			 * @type {function(): (boolean|Promise<boolean>)}
			 */
			normalizercx: {
				type: Boolean,
				default: false,
			},

			tips: {
				type: String,
				default: '请选择'
			},
			width: {
				type: String,
				default: '220px'
			},
			able: {
				type: Boolean,
				default: false
			},
			branchNodes: {
				type: Boolean,
				default: false
			},
			id: {
				type: String,
				default: null
			}
		},
		data() {
			return {
				deptOptions: [],
				deptId: this.id
			}
		},
		created() {
			this.getDeptTree();

		},
		methods: {
			/** 查询部门下拉树结构 */
			getDeptTree() {
				deptTreeSelect({
					'aboveNode': this.level
				}).then(response => {
					this.deptOptions = response.data;
					if (this.deptOptions.length > 0) {
						// 设置默认选中第一个节点的 ID
						this.deptId = this.deptOptions[0].id;
						this.$emit('deptCallback', this.deptOptions[0]);
						this.$store.dispatch('dept/updateSelectedDeptId', this.deptId);
						var dept = {
							"id": response.data[0].id,
							"label": response.data[0].label,
							"parentId": response.data[0].parentId,
							"type": response.data[0].type
						}
						Cookies.set("selDeptData", JSON.stringify(dept));
						// cookieStore.set("deptData",JSON.stringify(this.deptOptions[0]));
					}
				});
			},
			normalizer(node) {
				if (this.normalizercx) {
					if (node.type !== "3" && node.type !== "4") {
						node['isDisabled'] = true;
					}
				}

			},
			change(val, data) {
				this.$emit('deptCallback', val);
				this.$store.dispatch('dept/updateSelectedDeptId', val.id);
				// this.$store.dispatch('dept/updateSelectedDept', val);
				// cookieStore.set("deptData",JSON.stringify(val));
				var dept = {
					"id": val.id,
					"label": val.label,
					"parentId": val.parentId,
					"type": val.type
				}
				Cookies.set("selDeptData", JSON.stringify(dept));
			},
			clean() {
				this.deptId = null
				this.$store.commit('clearSelectedDeptId');

				// this.$eventBus.$emit('someEvent', null);
				// this.$emit('deptClean', this.deptId);
			}
		}
	}
</script>

<style lang="scss" scoped>

</style>